package logic

import (
	"context"
	"fmt"

	"probe-scheduler/internal/svc"
	pb "probe-scheduler/pb/scheduler"

	"github.com/zeromicro/go-zero/core/logx"
)

type BatchDeleteTaskLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBatchDeleteTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BatchDeleteTaskLogic {
	return &BatchDeleteTaskLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BatchDeleteTaskLogic) BatchDeleteTask(in *pb.BatchDeleteTaskRequest) (*pb.BatchDeleteTaskResponse, error) {
	// 1. 参数校验
	if len(in.TaskIds) == 0 {
		return &pb.BatchDeleteTaskResponse{
			Base: &pb.CommonResponse{
				Success: false,
				Message: "任务ID列表不能为空",
			},
			SuccessCount: 0,
			FailCount:    0,
		}, nil
	}

	// 2. 先从调度器移除所有任务（即使数据库删除失败，也停止任务执行）
	for _, taskID := range in.TaskIds {
		l.svcCtx.Scheduler.DeleteTask(taskID)
	}

	// 3. 批量删除数据库记录
	successCount, failDetails, err := l.svcCtx.TaskDao.BatchDeleteTask(l.ctx, in.TaskIds)
	failCount := len(failDetails)

	// 4. 构建响应结果
	baseResp := &pb.CommonResponse{
		Success: true,
		Message: fmt.Sprintf("批量删除完成：成功%d个，失败%d个", successCount, failCount),
	}
	if err != nil {
		baseResp.Success = false
		baseResp.Message = fmt.Sprintf("批量删除部分失败：%v", err)
	}

	return &pb.BatchDeleteTaskResponse{
		Base:         baseResp,
		SuccessCount: successCount,
		FailCount:    int32(failCount),
		FailDetails:  failDetails,
	}, nil
}
